//
//  EmoticonPackage.swift
//  表情键盘
//
//  Created by 林柱强 on 16/2/27.
//  Copyright © 2016年 林柱强. All rights reserved.
//

/*
结构：
1.加载emoticons.plist拿到每组表情的路径
emoticons.plist    -> 存储了所有组的表情数据(字典)
    |-packages     -> 字典数组
        |-id       -> 存储了对应组表情的文件夹
2.根据拿到的路径加载对应组表情的info.plist
info.plist(字典)
  |-id             -> 当前组文件夹的名称
  |-group_name_cn  -> 组的名称
  |-emoticon       -> 字典数组，里面存储了所有表情
       |-chs       -> 表情对应的文字
       |-png       -> 表情对应的图片
       |-code      -> emoji表情对应的十六进制字符串
*/

import UIKit

class EmoticonPackage: NSObject {
    /// 当前组文件夹的名称
    var id: String?
    /// 组的名称
    var group_name_cn: String?
    /// 当前组所有表情对象
    var emoticons: [Emoticon]?
    
    static let packageList: [EmoticonPackage] = EmoticonPackage.loadPackage()
    
    private class func loadPackage() -> [EmoticonPackage] {
        var packages = [EmoticonPackage]()
        //创建最近组
        let least = EmoticonPackage(id: "")
        least.group_name_cn = "最近"
        least.emoticons = [Emoticon]()
        least.appendEmptyEmoticons()
        packages.append(least)
        
        let path = NSBundle.mainBundle().pathForResource("emoticons.plist", ofType: nil, inDirectory: "Emoticons.bundle")!
        //1.加载emoticons.plist
        let dict = NSDictionary(contentsOfFile: path)!
        //2.从emoticons中获取packages
        let dictArray = dict["packages"] as! [[String: AnyObject]]
        //3.遍历packages
        
        for d in dictArray {
            //取出id创建对应的组
            let package = EmoticonPackage(id: d["id"] as! String)
            packages.append(package)
            package.loadEmoticons()
            package.appendEmptyEmoticons()
        }
        //4.取出ID
        return packages
    }
    /**
     加载每一组中所有的表情
     */
    func loadEmoticons() {
        let emoticonDict = NSDictionary(contentsOfFile: infoPath("info.plist"))!
        group_name_cn = emoticonDict["group_name_cn"] as? String
        let dictArray = emoticonDict["emoticons"] as! [[String : String]]
        emoticons = [Emoticon]()
        var index = 0
        for dict in dictArray {
            if index == 20 {
                emoticons?.append(Emoticon(isRemoveButton: true))
                index = 0
            }
            emoticons?.append(Emoticon(dict: dict, id: id!))
            index++
        }
    }
    /**
     追加空白按钮 
     如果不足21个，那么就添加一些空白按钮
     */
    func appendEmptyEmoticons() {
        let count = emoticons!.count % 21
        
        //追加空白按钮
        for _ in count..<20 {
            emoticons?.append(Emoticon(isRemoveButton: false))
        }
        //追加一个删除按钮
        emoticons?.append(Emoticon(isRemoveButton: true))
        
    }
    /**
     用于给最近组添加表情
     */
    func appendEmoticon(emoticon: Emoticon) {
        //判断是否为删除按钮
        if emoticon.isRemoveButton {
            return
        }
        //判断此表情是否已经添加进最近组中
        let contains =  emoticons!.contains(emoticon)
        if !contains {
            //删除删除按钮
            emoticons?.removeLast()
            emoticons?.append(emoticon)
        }
        //给最近组的表情排序
        var result = emoticons?.sort({ (e1, e2) -> Bool in
            return e1.times > e2.times
        })
        //删除最后一个表情
        if !contains {
            result?.removeLast()
            result?.append(Emoticon(isRemoveButton: true))
        }
        
        emoticons = result
    }
    
    /**
     获取指定文件的全路径
     
     - returns: 全路径
     */
    func infoPath(fileName: String) -> String {
        return (EmoticonPackage.emoticonPath().stringByAppendingPathComponent(id!) as NSString).stringByAppendingPathComponent(fileName)
    }
    
    /**
     获取微博表情的主路径
     */
    class func emoticonPath() -> NSString {
        return (NSBundle.mainBundle().bundlePath as NSString).stringByAppendingPathComponent("Emoticons.bundle")
    }
    
    
    init(id: String) {
        self.id = id
    }
}


class Emoticon: NSObject {
 /// 表情对应的文字
    var chs: String?
 /// 表情对应的图片
    var png: String? {
        didSet{
            imagePath = (EmoticonPackage.emoticonPath().stringByAppendingPathComponent(id!) as NSString).stringByAppendingPathComponent(png!)
        }
    }
 /// emoji表情对应的十六进制字符串
    var code: String? {
        didSet {
            //从字符串中取出十六进制的数
            //创建一个扫描器，扫描器可以从字符串中提取我们想要的数据
            let scanner = NSScanner(string: code!)
            //将十六进制转换为字符串
            var result: UInt32 = 0
            scanner.scanHexInt(&result)
            //将十六进制转换为emoji字串符
            emojiStr = "\(Character(UnicodeScalar(result)))"
        }
    }
    
    var emojiStr: String?
 /// 当前表情的文件夹
    var id: String?
    /// 表情图片的全路径
    var imagePath: String?
    /// 标记是否为删除按钮
    var isRemoveButton: Bool = false
    /// 记录当前表情被使用的次数
    var times: Int = 0
    
    init(isRemoveButton: Bool) {
        super.init()
        self.isRemoveButton = isRemoveButton
    }
    
    init(dict: [String : String], id: String) {
        self.id = id
        super.init()
        setValuesForKeysWithDictionary(dict)
        
    }
    
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {
        
    }
}